/**
 * Created by PanJiaChen on 16/11/18.
 */

import { Toast } from 'vant'
import axios from 'axios'
import * as dd from 'dingtalk-jsapi'

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"').replace(/\+/g, ' ') +
      '"}'
  )
}
/*
 * 是否html
 * */
export function isHTML(str) {
  var a = document.createElement('div')
  a.innerHTML = str

  for (var c = a.childNodes, i = c.length; i--; ) {
    if (c[i].nodeType == 1) return true
  }

  return false
}
/*
 * 过滤html标签
 * */
export function filterHTML(val) {
  if (val != null && val != '') {
    var re1 = new RegExp('<.+?>|&.+?;', 'g') //匹配html标签的正则表达式，"g"是搜索匹配多个符合的内容
    var msg = val.replace(re1, '') //执行替换成空字符
    msg = msg.replace(/\s/g, '') //去掉所有的空格（中文空格、英文空格都会被替换）
    msg = msg.replace(/[\r\n]/g, '') //去掉所有的换行符
    return msg.substr(0, 100) //获文本文字内容的前100个字符
  } else return ''
}
export const Tips = {
  error: message => {
    Toast({ message, icon: 'clear', className: 'toast-error' })
  },
  warning: message => {
    Toast({ message, icon: 'warning', className: 'toast-warning' })
  },
  success: message => {
    Toast({ message, icon: 'checked', className: 'toast-success' })
  },
  loading: message => {
    Toast.loading({
      forbidClick: true,
      message: message ? message : '加载中...',
      duration: 0,
      className: 'toast-loading'
    })
  }
}
/*
 * 获取文件后缀
 * */
export function fileSuffix(fileName) {
  const fileType = {
    image: ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'tif', 'tiff'],
    doc: ['doc'],
    docx: ['docx'],
    video: ['wmv', 'rm', 'rmvb', 'mpg', 'mpeg', 'mpe', '3gp', 'mov', 'mp4', 'm4v', 'avi', 'mkv', 'flv', 'vob'],
    excel: ['xls', 'xlsx'],
    pdf: ['pdf'],
    ppt: ['pptx', 'ppt'],
    txt: ['text', 'txt']
  }
  const suffix = fileName ? fileName.substring(fileName.lastIndexOf('.') + 1) : ''
  var result = 'question'
  for (let key in fileType) {
    for (var i = 0; i < fileType[key].length; i++) {
      if (fileType[key][i] === suffix) {
        result = key
        break
      }
    }
  }
  return result
}
/*
 * 是否base64
 * */
export function isBase64(str) {
  if (str === '' || str.trim() === '') {
    return false
  }
  try {
    return btoa(atob(str)) == str
  } catch (err) {
    return false
  }
}
export function createShortPhone(num) {
  if (/^\d{4,5}$/.test(num)) {
    return 66 + num
  } else {
    return ''
  }
}

/*
 * 下载文件
 * */
export function download(url, file_name) {
  return new Promise(function (resolve, reject) {
    Tips.loading('下载文件中...')
    if (dd.env.platform !== 'notInDingTalk') {
      // 钉钉免密登录
      dd.ready(() => {
        dd.biz.util.downloadFile({
          url: url, //要下载的文件的url
          name: file_name, //定义下载文件名字
          onProgress: function (msg) {
            console.log(msg)
            // 文件下载进度回调
          },
          onSuccess: function (result) {
            console.log(result)
            alert(result)
            /*
              true
            */
          },
          onFail: function (err) {
            alert(err)
          }
        })
      })
    } else {
      axios
        .get(url, {
          baseURL: '',
          responseType: 'blob'
        })
        .then(function (res) {
          console.log(res)
          const { data, headers } = res
          let fileName = file_name
          const blob = new Blob([data], { type: headers['content-type'] })
          let dom = document.createElement('a')
          let url = window.URL.createObjectURL(blob)
          dom.href = url
          dom.download = decodeURI(fileName)
          dom.style.display = 'none'
          document.body.appendChild(dom)
          dom.click()
          dom.parentNode.removeChild(dom)
          window.URL.revokeObjectURL(url)
          resolve(res)
          Toast.clear()
        })
        .catch(function (err) {
          reject(err)
          Toast.clear()
          Tips.error('下载失败')
        })
    }
  })
}
/*
 * 获取图片地址
 * */
export function getImgUrl(con) {
  const imgReg = /<img.*?(?:>|\/>)/gi // 匹配图片中的img标签
  const srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i // 匹配图片中的src
  const ImageArr = con.match(imgReg) || [] // 筛选出所有的img
  const ImageSrcArr = [] // 图片地址数组
  for (let i = 0; i < ImageArr.length; i++) {
    const imgSrc = ImageArr[i].match(srcReg)
    // 获取图片地址
    ImageSrcArr.push(imgSrc[1])
  }
  return ImageSrcArr
}
